package hn.cch.druid.configuration;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import hn.cch.druid.repository.DruidRepositoryFactoryBean;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.dao.annotation
        .PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @author CCH
 * @version 2018.08.30
 */

@Order(Ordered.HIGHEST_PRECEDENCE)
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
@EnableJpaRepositories(basePackages = "hn.cch.druid.repository", repositoryFactoryBeanClass = DruidRepositoryFactoryBean.class)
@EntityScan(basePackages = "hn.cch.druid.entity")
public class DruidConfiguration {

    @Bean
    PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor(){
        return new PersistenceExceptionTranslationPostProcessor();
    }

    @Bean
    public ServletRegistrationBean servletRegistrationBean() {

        ServletRegistrationBean servletRegistrationBean = new
                ServletRegistrationBean(new StatViewServlet(), "/druid/*");

        servletRegistrationBean.addInitParameter("allow", "192.168.18.100,127.0.0.1");
        servletRegistrationBean.addInitParameter("deny", "");

        servletRegistrationBean.addInitParameter("loginUsername", "cch");
        servletRegistrationBean.addInitParameter("loginPassword", "cch");

        servletRegistrationBean.addInitParameter("resetEnable", "false");

        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new
                FilterRegistrationBean(new WebStatFilter());

        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*" +
                ".jpg,*.png,*.css,*.ico,/druid/*");

        return filterRegistrationBean;
    }
}
